#include "votesys.h"
#include<stdio.h>
#include<string.h>
#include<assert.h>
#include<stdlib.h>
#define LEN 80
#define MAXNETNAMELEN 255 

static void 
marshal_submitvote(char *lm, NetMessage *msg)
{
  if(msg == NULL || lm == NULL)
     return;

  msg->length = strlen(lm);
  strcpy(msg->data, lm) == NULL;
}

static void
unmarshal_submitvote(voteStatus* status, NetMessage msg, char *token)
{
  if( status == NULL )
    return;

  sscanf(msg.data, "%d %s", status, token);
}


int 
main(int argc, char* argv[])
{
  CLIENT *cl;
  voteStatus status;
  int i;
  char *name;
  NetMessage msg, stat;
  char servername[MAXNETNAMELEN];
  char token[MAXLENTOKEN];
  struct timeval tv; 

  name = (char*)malloc(sizeof(char)*LEN);
 

  if(argc < 2)
  {
    fprintf(stderr, "Please input the name of artist\n"); 
    return -1;
  }
  
  cl = clnt_create("localhost", VOTESYS, VOTEVERS, "tcp");
  
  if( cl == NULL )
  {
     clnt_pcreateerror("Server"); 
     return -1;
  }

  name[0] = '\0';
  for(i=1; i<argc; i++)
  {
    assert(strcat(name, argv[i]) != (char*)NULL);   
  }
  
  /*destory previous auth*/
  auth_destroy(cl->cl_auth);

  cl->cl_auth = authsys_create_default();
  
  //set timeout
  tv.tv_sec = 1;
  tv.tv_usec = 0;
  clnt_control(cl, CLSET_TIMEOUT, &tv);

  marshal_submitvote(name, &msg);
  if( vote_1(&msg, &stat, cl) != RPC_SUCCESS )
  { 
      //clnt_perror(cl, "Server"); 
      fprintf(stderr, "Submit unsuccessfully\n");
      return -1;
  }
 

  unmarshal_submitvote(&status, stat, token);
  if( status == vsInvalidVoter )
  {
    printf("The voting is close\n");

  }
  else
  {
   printf("submitVote: your token is %s\n", token);
  }


  return 0;

}
